"use client";

import React, {
  createContext,
  useContext,
  ReactNode,
  useState,
  useEffect,
} from "react";
import {
  AuthContextType,
  LoginRequest,
  LoginResponse,
  UserInfo,
  ValidateTokenRequest,
  ValidateTokenResponse,
} from "@/lib/types";

const AuthContext = createContext<AuthContextType | undefined>(undefined);

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8013";
// 添加认证服务器URL的环境变量配置
const AUTH_SERVER_URL = process.env.NEXT_PUBLIC_AUTH_SERVER_URL || "http://localhost:8013/auth";

// 用于gid认证的接口定义
interface GidLoginResponse {
  success: boolean;
  token?: string;
  userId?: string;
  message?: string;
}

// 从URL参数中获取gid
const getGidFromUrl = (): string | null => {
  try {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get("gid");
  } catch (e) {
    console.error("获取URL参数失败:", e);
    return null;
  }
};

// 清除URL中的所有参数
const removeGidFromUrl = () => {
  try {
    // 只保留路径名，移除所有查询参数
    const newUrl = window.location.pathname;
    // 使用replaceState避免添加到浏览历史
    console.log(`newUrl${newUrl}`);
    window.history.replaceState({}, document.title, newUrl);
  } catch (e) {
    console.error("移除URL参数失败:", e);
  }
};
// 检查远程认证服务器可用性
const checkRemoteAuthAvailability = async (): Promise<boolean> => {
  try {
    console.log("检查远程认证服务器可用性:", AUTH_SERVER_URL);
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 3000); // 3秒超时
    
    const response = await fetch(`${AUTH_SERVER_URL}/health`, {
      method: "GET",
      signal: controller.signal,
      headers: {
        "Content-Type": "application/json",
      },
    });
    
    clearTimeout(timeoutId);
    const isAvailable = response.ok;
    console.log("远程认证服务器可用性:", isAvailable);
    return isAvailable;
  } catch (error) {
    console.log("远程认证服务器不可用:", error);
    return false;
  }
};
export function AuthProvider({ children }: { children: ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState<UserInfo | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 初始化时检查URL中的gid参数
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const urlParams = new URLSearchParams(window.location.search);
        const hasGid = urlParams.has("gid");

        // 调试日志
        console.log("AuthRedirect Check:", {
          hasGid,
          href: window.location.href,
        });

        if (!hasGid) {
          // 如果没有gid参数，重定向到认证服务器
          const isRemoteAuthAvailable = await checkRemoteAuthAvailability();
          if (!isRemoteAuthAvailable) {
            setError("认证服务器不可用");
            return;
          }
          const encodedUrl = encodeURIComponent(window.location.href);
          window.location.href = `https://shai438a.ad005.onehc.net:5080/auth?returnUrl=${encodedUrl}`;
          // console.log("Redirecting to Auth Server...");
          return;
        }

        // 如果有gid参数，尝试使用gid进行认证
        const gid = getGidFromUrl();
        if (gid) {
          // 使用gid作为token和用户ID（简化实现，无需后端请求）
          const mockToken = gid;
          const mockUserId = gid;

          setToken(mockToken);
          setIsAuthenticated(true);
          localStorage.setItem("auth_token", mockToken);

          // 设置用户信息
          setUser({
            userId: mockUserId,
            username: `user_${mockUserId.substring(0, 8)}`,
            created_at: new Date().toISOString(),
          });

          // 移除URL中的gid参数
          removeGidFromUrl();

          console.log(`Gid认证成功，用户已登录，${mockUserId}`);
        } else {
          console.error("Gid参数存在但获取失败");
        }
      } catch (error) {
        console.error("Auth check failed:", error);
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, []);

  // 登录函数
  const login = async (
    username: string,
    password: string,
  ): Promise<boolean> => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`${API_BASE_URL}/auth/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, password } as LoginRequest),
      });

      const data: LoginResponse = await response.json();

      if (data.success && data.token && data.userId) {
        setToken(data.token);
        setIsAuthenticated(true);
        localStorage.setItem("auth_token", data.token);

        // 获取用户信息
        await fetchUserInfo(data.token);
        return true;
      } else {
        setError(data.message || "登录失败");
        return false;
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "网络错误");
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 登出函数
  const logout = async () => {
    try {
      if (token) {
        await fetch(`${API_BASE_URL}/auth/logout`, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
      }
    } catch (err) {
      console.error("登出请求失败:", err);
    } finally {
      setToken(null);
      setUser(null);
      setIsAuthenticated(false);
      localStorage.removeItem("auth_token");
    }
  };

  // 验证token
  const validateToken = async (tokenToValidate?: string): Promise<boolean> => {
    const currentToken = tokenToValidate || token;
    if (!currentToken) {
      setIsLoading(false);
      return false;
    }

    try {
      console.log("开始验证token:", currentToken.substring(0, 10) + "...");
      const response = await fetch(`${API_BASE_URL}/auth/validate`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ token: currentToken } as ValidateTokenRequest),
      });

      if (!response.ok) {
        console.error("Token验证请求失败，状态码:", response.status);
        logout();
        return false;
      }

      const data: ValidateTokenResponse = await response.json();
      console.log("Token验证结果:", data);

      if (data.valid) {
        setIsAuthenticated(true);
        console.log("开始获取用户信息...");
        await fetchUserInfo(currentToken);
        console.log("用户信息获取完成");
        return true;
      } else {
        console.log("Token无效，执行登出");
        logout();
        return false;
      }
    } catch (err) {
      console.error("Token验证失败:", err);
      logout();
      return false;
    } finally {
      console.log("设置加载状态为false");
      setIsLoading(false);
    }
  };

  // 获取用户信息
  const fetchUserInfo = async (authToken: string) => {
    try {
      console.log("正在获取用户信息...");
      const response = await fetch(`${API_BASE_URL}/auth/user`, {
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });

      console.log("用户信息API响应状态:", response.status);

      if (response.ok) {
        const userData: UserInfo = await response.json();
        console.log("获取到用户信息:", userData);
        setUser(userData);
      } else {
        console.error("获取用户信息失败，状态码:", response.status);
        const errorText = await response.text();
        console.error("错误响应:", errorText);
        // 即使获取用户信息失败，也不应该阻止登录流程
        // 设置一个默认的用户信息
        setUser({
          userId: "unknown",
          username: "unknown",
          created_at: new Date().toISOString(),
        });
      }
    } catch (err) {
      console.error("获取用户信息失败:", err);
      // 设置默认用户信息，避免阻塞登录流程
      setUser({
        userId: "unknown",
        username: "unknown",
        created_at: new Date().toISOString(),
      });
    }
  };

  const contextValue: AuthContextType = {
    isAuthenticated,
    user,
    token,
    login,
    logout,
    validateToken: () => validateToken(),
    isLoading,
    error,
  };

  return (
    <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
  );
}

export function useAuth(): AuthContextType {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
}
